"""
先导入模块
"""
import telnetlib
import time
import threading
import re


def save_huawei_config(host='', username='', password=''):
    # 将IP地址,用户名，密码分别赋给变量host，username,password

    tn = telnetlib.Telnet(host)

    # 输入用户名和密码登入设备
    tn.read_until(b"Username:")
    tn.write(username.encode("ascii") + b"\n")
    tn.read_until(b"Password:")
    tn.write(password.encode("ascii") + b"\n")

    # 执行命令
    # 滚动显示
    tn.write(b"screen-length 0 temporary \n")
    tn.write(b"display cur\n")
    # tn.read_all()
    time.sleep(5)
    file = "%s_%s.txt" % (host, time.strftime("%Y-%m-%d_%H-%M-%S"))
    # 显示结果
    print("主机：%s 配置已保存为 %s" % (host, file))
    print(tn.read_very_eager().decode("ascii"), file=open(file, 'w+'), end='')
    tn.close()


def save_cisco_config(host='', username='', password=''):
    # 将IP地址,用户名，密码分别赋给变量host，username,password

    tn = telnetlib.Telnet(host)

    # 输入用户名和密码登入设备
    tn.read_until(b"Username:")
    tn.write(username.encode("ascii") + b"\n")
    tn.read_until(b"Password:")
    tn.write(password.encode("ascii") + b"\n")

    # 执行命令
    # 滚动显示
    tn.write(b"terminal length 0 \n")
    tn.write(b"show run\n")
    # tn.read_all()
    time.sleep(5)
    file = "%s_%s.txt" % (host, time.strftime("%Y-%m-%d_%H-%M-%S"))
    # 显示结果
    print("主机：%s 配置已保存为 %s" % (host, file))
    print(tn.read_very_eager().decode("ascii"), file=open(file, 'w+'), end='')
    tn.close()


if __name__ == '__main__':
    for i in open("a.txt"):
        """
        遍历ip地址、用户名、密码
        格式如下：
            10.0.0.2 admin admin
            10.0.0.3 admin admin
        """
        thread_list = []
        line = re.split('[ ,]*', i)
        if len(line) == 3:
            t = threading.Thread(target=save_huawei_config, args=(line[0], line[1], line[2]))
            t.start()
